<?php
function success($msg)
{
    $res = 'success';
    require ROOT . '/view/admin/info.html';
    exit();
}

function error($msg)
{
    $res = 'error';
    require ROOT . '/view/admin/info.html';
    exit();
}

/**
 * @param $total 记录数
 * @param $pageSize 页大小
 * @param $currentPage 当前页
 * @return array
 * 分页工具
 */
function pages($total, $pageSize, $currentPage = 1)
{
    $pageCount = ceil($total / $pageSize);

    $left = $currentPage - 2;
    $left = max(1, $left);

    $right = $left + 4;
    $right = min($pageCount, $right);

    $left = $right - 4;
    $left = max(1, $left);

    $pages = [];
    for ($i = $left; $i <= $right; $i++) {
        $_GET['page'] = $i;
        $pages[$i] = http_build_query($_GET);
    }
    return $pages;
}


/** * 获取来访者IP * @return $realip IP值 */
function getIp()
{
    static $realip = NULL;
    if ($realip !== NULL) {
        return $realip;
    }
    if (getenv('HTTP_X_FORWARDED_FOR')) {
        $realip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif (getenv('HTTP_CLIENT_IP')) {
        $realip = getenv('HTTP_CLIENT_IP');
    } else {
        $realip = getenv('REMOTE_ADDR');
    }
    return $realip;
}

/**
 * @param $str
 * @return string
 * 获取文件后缀名
 */
function get_ext($str)
{
    return strrchr($str, '.');
}

/**
 * @param int $length
 * @return bool|string
 * 随机生成一串字符
 */
function randStr($length = 6)
{
    $str = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
    return substr(str_shuffle($str), 0, $length);
}

function createDir()
{
    $path = date('Ymd');
    return (is_dir(ROOT . '/upload/' . $path) || mkdir(ROOT . '/upload/' . $path, 0777, true)) ? $path : false;
}

function uploadFile($name)
{
    $path = createDir();
    $path = '/upload/' . $path . '/' . randStr() . get_ext($_FILES[$name]['name']);
    $res = move_uploaded_file($_FILES['pic']['tmp_name'], ROOT . $path);
    return $res ? $path : false;
}

function UnicodeEncode($str)
{
    preg_match_all('/./u', $str, $matches);
    $unicodeStr = "";
    foreach ($matches[0] as $m) {
        //修改
        //$unicodeStr .= "&#".base_convert(bin2hex(iconv('UTF‐8',"UCS‐4",$m)),16,10);
        $unicodeStr .= "\u" . base_convert(bin2hex(iconv('UTF-8', "UCS-4", $m)), 16, 16);
    }
    return $unicodeStr;
}

//$str = "新浪微博";
//echo UnicodeEncode($str);

function unicodeDecode($unicode_str)
{
    $json = '{"str":"' . $unicode_str . '"}';
    $arr = json_decode($json, true);
    if (empty($arr)) return '';
    return $arr['str'];
}

//
//$unicode_str = "\u65b0\u6d6a\u5fae\u535a";
//echo unicodeDecode($unicode_str);


function randStr2($length = 4)
{
    $str = '飞机扣发来的咖啡机热武器哦表学位网品牌区二层';
    $str = preg_replace('/[^\x{4e00}-\x{9fa5}]/u', '', $str);//剔除非uft8汉字
    $str = chunk_split($str, 3, ',');
    $arr = explode(',', $str);
    shuffle($arr);
    $str = implode($arr);
    $str = mb_substr($str, 0, $length, 'utf-8');
    return $str;
}

function verify()
{
    $im = imagecreatetruecolor(100, 50);
    $red = imagecolorallocate($im, 255, 0, 0);
    $blue = imagecolorallocate($im, 0, 0, 255);
    imagefill($im, 0, 0, $red);
    $font = 'C:\Windows\Fonts\simkai.ttf';
    $code = randStr2(4);
    imagefttext($im, 15, 6, 10, 30, $blue, $font, $code);
    // 绘制干扰线
    for ($i = 0; $i < 5; $i++) {
        $lineColor = imagecolorallocate($im, rand(50, 200), rand(50, 200), rand(50, 200));
        imageline($im, rand(0, 120), rand(0, 40), rand(0, 100), rand(0, 20), $lineColor);
    }
// 绘制干扰点
    for ($i = 0; $i < 100; $i++) {
        $pointColor = imagecolorallocate($im, rand(50, 200), rand(50, 200), rand(50, 200));
        imagesetpixel($im, rand(1, 119), rand(1, 39), $pointColor);
    }
    $path = '/tmp/' . md5($code . time()) . '.png';
    imagepng($im, ROOT . $path);
    imagedestroy($im);
    setcookie('code', $code);
    setcookie('code_path', $path);
    return $path;
}

/**
 * @param $ori 原图地址
 * @param int $sw 缩略图宽度
 * @param int $sh 缩略图高度
 * @return string 缩略图地址
 * 缩略图
 */
function thumb($ori, $sw = 200, $sh = 200)
{
    list($bw, $bh, $type) = getimagesize($ori);
    $map = [
        1 => 'imagecreatefromgif',
        2 => 'imagecreatefromjpeg',
        3 => 'imagecreatefrompng',
    ];
    if (!isset($map[$type])) {
        echo '格式错误';
        exit();
    }
    $big = $map[$type]($ori);
    $small = imagecreatetruecolor($sw, $sh);
    $red = imagecolorallocatealpha($small, 255, 0, 0, 127);
    imagealphablending($small, false);
    imagefill($small, 0, 0, $red);
    $rate = min($sw / $bw, $sh / $bh);
    $rw = $bw * $rate;
    $rh = $bh * $rate;
    imagecopyresampled($small, $big, ($sw - $rw) / 2, ($sh - $rh) / 2, 0, 0, $rw, $rh, $bw, $bh);
    imagesavealpha($small, true);
    $path = '/upload/' . date('Ymd') . '/thumb_' . substr(strrchr($ori, '/'), 1);
    imagepng($small, ROOT . $path);
//    header('content-type:image/jpeg');
//    imagepng($small);
    imagedestroy($small);
    imagedestroy($big);
    return $path;
}

//thumb('../images/bg.jpg');

/**
 * 权限控制；游客用户可访问的页面，其他页面需登录
 */
function access()
{
    $allow_list = ['/Index.php', '/art.php', '/login.php', '/loginout.php'];
    /*    if(!isset($_COOKIE['username'])&&!in_array($_SERVER['DOCUMENT_URI'],$allow_list)){
            echo '请先登录';
            header('refresh:2;url=login.php');
            exit();
        }
    */
    /*session_start();
    if (!in_array($_SERVER['DOCUMENT_URI'], $allow_list)) {
        if (isset($_SESSION['id'])) {
            if ($_SESSION['id'] != session_id()) {
                echo '请先登录1';
//                header('refresh:2;url=login.php');
                exit();
            }
        } else {
            echo '请先登录2';
//            header('refresh:2;url=login.php');
            exit();
        }
    }*/
    //nginx:DOCUMENT_URI  apache:PHP_SELF
    if (!in_array($_SERVER['DOCUMENT_URI'], $allow_list)) {
        if(isset($_COOKIE['id'])&&isset($_COOKIE['ccode'])){
            $password=mGetOne("select password from user where user_id=$_COOKIE[id];");
            if($_COOKIE['ccode']!=$password){
                echo '请先登录2';
            header('refresh:2;url=login.php');
                exit();
            }
        }else{
            echo '请先登录2';
            header('refresh:2;url=login.php');
            exit();
        }
    }
}

/** *
 *.过滤非法字符
 * 转义字符串，对post,get,cookie数组进行转义
 */
function _addslashes($arr)
{
    foreach ($arr as $k => $v) {
        if (is_string($v)) {
            $arr[$k] = addslashes($v);
        } elseif (is_array($v)) {
            $arr[$k] = _addslashes($v);
        }
    }
    return $arr;
}